import hashlib
import json
from time import time
import os

class Blockchain(object):
    def new_block(self, chain, msg, previous_hash=None):
        """
        创建一个新的区块到区块链中
        :param proof: <int> 由工作证明算法生成的证明
        :param previous_hash: (Optional) <str> 前一个区块的 hash 值
        :return: <dict> 新区块
        """
        block = {
            'index': len(chain) + 1,
            'timestamp': time(),
            'mag': msg,#核心记录是一个字典
            'previous_hash': previous_hash or self.hash(chain[-1]),
        }
        return block

    '''def new_transaction(self, sender, recipient, amount):
        """
        创建一笔新的交易到下一个被挖掘的区块中
        :param sender: <str> 发送人的地址
        :param recipient: <str> 接收人的地址
        :param amount: <int> 金额
        :return: <int> 持有本次交易的区块索引
        """
        self.current_transactions.append({
            'sender': sender,
            'recipient': recipient,
            'amount': amount,
        })

        return self.last_block['index'] + 1
        '''
    '''将聊天记录写入区块链'''
    def record(self, name, msg):
        if os.path.exists( name+ '.json'):
            with open(name + '.json', "r", encoding='utf-8') as f:
                chain = json.load(f)
                new_record = self.new_block(chain=chain, msg=msg,)
                chain.append(new_record)
            with open(name + '.json', "w", encoding='utf-8') as f:  ## 设置'utf-8'编码
                f.write(json.dumps(chain, ensure_ascii=False, sort_keys=True))
        else:
            chain = []
            new_record = self.new_block(previous_hash=1,  chain=chain, msg=msg)
            chain.append(new_record)
            with open(name + '.json', "w", encoding='utf-8') as f:  ## 设置'utf-8'编码
                f.write(json.dumps(chain, ensure_ascii=False, sort_keys=True))
        return new_record
    @property
    def last_block(self):
        return self.chain[-1]

    @staticmethod
    def hash(block):
        """
        给一个区块生成 SHA-256 值
        :param block: <dict> Block
        :return: <str>
        """

        # 我们必须确保这个字典（区块）是经过排序的，否则我们将会得到不一致的散列
        block_string = json.dumps(block, sort_keys=True).encode()
        return hashlib.sha256(block_string).hexdigest()


